package com.study.book.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.util.StringUtils;
import com.study.book.common.R;
import com.study.book.mapper.AdminMapper;
import com.study.book.mapper.LibrarySeatDetailMapper;
import com.study.book.pojo.*;
import com.study.book.res.req.LoginDtoWeb;
import com.study.book.res.req.LoginReqVo;
import com.study.book.service.*;
import com.study.book.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;

@Api(tags = "后台管理接口")
@RestController
@RequestMapping("/app/Mange")
public class MangeController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private JwtUtils jwtUtils;

    @Resource
    private ForumService forumService;

    @Autowired
    private LibrarySeatDetailMapper librarySeatDetailMapper;

    @Resource
    private CommentService commentService;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private CarouselService carouselService;

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductService productService;

    @Autowired
    private LibraryService libraryService;


    @Autowired
    private AreaService areaService;


    @ApiOperation("后台管理用户登录")
    @PostMapping("/login")
    public R appLogin(@RequestBody LoginDtoWeb vo) {
        if (Strings.isEmpty(vo.getUsername()) || Strings.isEmpty(vo.getPassword())) {
            return R.error("用户名或密码不能为空");
        }
        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getPhone, vo.getUsername()).eq(Admin::getType, vo.getType());
        Admin admin = adminService.getOne(adminLambdaQueryWrapper);
        if (admin == null) {
            return R.error("用户名或密码错误");
        } else {
            if (admin.getPassword().equals(vo.getPassword())) {
                return R.ok("success", jwtUtils.generateToken(admin.getType() + admin.getId().toString()));
            } else {
                return R.error("用户名或密码错误");
            }
        }

    }

    @ApiOperation("当前登录管理员用户信息")
    @GetMapping("/userInfo")
    public R<Admin> userInfo(HttpServletRequest request) {
        String id = (String) request.getAttribute("userId");
        return adminService.userInfo(id);
    }

    @ApiOperation("获取所有普通用户信息")
    @PostMapping("/allUserInfo")
    public R allUserInfo(HttpServletRequest request, @RequestBody Integer currentPage) {
        String type = (String) request.getAttribute("type");
        if (type.equals("1")) {
            LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Admin::getType, "0");
            Page<Admin> page = new Page<>(currentPage, 10);
            Page<Admin> adminList = adminService.list(lambdaQueryWrapper, page);
            adminList.getRecords().replaceAll(e -> e.setPassword(""));
            adminList.getRecords().replaceAll(e -> e.setType("用户"));
            return R.ok(adminList);
        } else return R.error("请登录管理员账号");
    }

    @ApiOperation("获取所有普通用户信息")
    @GetMapping("/queryUserInfo/{pageIndex}/{search}")
    public R queryUserInfo(HttpServletRequest request, @PathVariable("pageIndex") Integer currentPage, @PathVariable("search") String word) {
        String type = (String) request.getAttribute("type");
        if (type.equals("1")) {
            LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Admin::getType, "0").like(Admin::getUsername, word).or().like(Admin::getPhone, word);
            Page<Admin> page = new Page<>(currentPage, 10);
            Page<Admin> adminList = adminService.list(lambdaQueryWrapper, page);
            adminList.getRecords().replaceAll(e -> e.setPassword(""));
            adminList.getRecords().replaceAll(e -> e.setType("用户"));
            return R.ok(adminList);
        } else return R.error("请登录管理员账号");
    }

    @ApiOperation("获取所有商家用户信息")
    @GetMapping("/queryLibraryUserInfo/{pageIndex}/{search}")
    public R queryLibraryUserInfo(HttpServletRequest request, @PathVariable("pageIndex") Integer currentPage, @PathVariable("search") String word) {
        String type = (String) request.getAttribute("type");
        if (type.equals("1")) {
            LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Admin::getType, "2").and(new Consumer<LambdaQueryWrapper<Admin>>() {
                @Override
                public void accept(LambdaQueryWrapper<Admin> adminLambdaQueryWrapper) {
                    adminLambdaQueryWrapper.like(Admin::getUsername, word).or().like(Admin::getPhone, word);
                }
            });
            Page<Admin> page = new Page<>(currentPage, 10);
            Page<Admin> adminList = adminService.list(lambdaQueryWrapper, page);
            adminList.getRecords().replaceAll(e -> e.setPassword(""));
            adminList.getRecords().replaceAll(e -> e.setType("商家"));
            return R.ok(adminList);
        } else return R.error("请登录管理员账号");
    }

    @ApiOperation("添加用户信息")
    @PostMapping("/addUser")
    public R addUser(HttpServletRequest request, @RequestBody Admin admin) {
        String type = (String) request.getAttribute("type");
        if (type.equals("1")) {

            if (admin.getId() == 0) admin.setId(null);
            if (StringUtils.isNullOrEmpty(admin.getPassword())) {
                Admin user = adminService.getById(admin.getId());
                admin.setPassword(user.getPassword());
            }
            adminService.saveOrUpdate(admin);
            return R.ok(admin);
        } else return R.error("请登录管理员账号");
    }

    @ApiOperation("添加商家信息")
    @PostMapping("/addUser/{libraryId}")
    public R addUser(HttpServletRequest request, @RequestBody Admin admin, @PathVariable("libraryId") Integer libraryId) {
        String type = (String) request.getAttribute("type");
        if (type.equals("1")) {

            if (admin.getId() == 0) admin.setId(null);
            if (StringUtils.isNullOrEmpty(admin.getPassword())) {
                Admin user = adminService.getById(admin.getId());
                admin.setPassword(user.getPassword());
            }
            adminService.saveOrUpdate(admin);
            return R.ok(admin);
        } else return R.error("请登录管理员账号");
    }


    @ApiOperation("删除用户")
    @PostMapping("/deleteUser")
    public R deleteUser(HttpServletRequest request, @RequestBody Integer adminId) {
        String type = (String) request.getAttribute("type");
        if (type.equals("1")) {
            return R.ok(adminService.removeById(adminId));
        } else return R.error("请登录管理员账号");
    }

    @ApiOperation("获取所有图书馆商家信息")
    @PostMapping("/allLibraryInfo")
    public R allLibraryInfo(HttpServletRequest request, @RequestBody Integer currentPage) {
        String type = (String) request.getAttribute("type");
        if (type.equals("1")) {
            LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Admin::getType, "2");

            Page<Admin> page = new Page<>(currentPage, 10);
            Page<Admin> adminList = adminService.list(lambdaQueryWrapper, page);
            adminList.getRecords().replaceAll(e -> e.setPassword(""));
            adminList.getRecords().replaceAll(e -> e.setType("商家"));

            return R.ok(adminList);
        } else return R.error("请登录管理员账号");
    }

    @ApiOperation("获取论坛列表")
    @GetMapping("/forumList")
    public R<List<Forum>> forumList() {
        return R.ok(forumService.list());
    }

    @ApiOperation("添加论坛信息")
    @PostMapping("/addForum")
    public R addForum(@RequestBody Forum forum) {
        forumService.saveOrUpdate(forum);
        return R.ok();
    }

    @ApiOperation("获取论坛详细内容")
    @GetMapping("/comment/{id}")
    public R<List<Comment>> comment(@PathVariable("id") int forumId) {
        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Comment::getForumid, forumId).orderByDesc(Comment::getSort);
        List<Comment> list = commentService.list(lambdaQueryWrapper);
        list.replaceAll(e -> {
            e.setAdminName(adminMapper.selectById(e.getAdminid()).getUsername());
            return e;
        });
        return R.ok(list);
    }

    @ApiOperation("获取当前轮播图列表")
    @GetMapping("/carouseList")
    public R<List<Carousel>> carouselList() {
        return R.ok(carouselService.list());
    }


    @ApiOperation("获取所有轮播图列表")
    @GetMapping("/carouseLists")
    public R<List<String>> carouselLists() throws IOException {

        org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:data/images/swipers/");
        File folder = resource.getFile();
        File[] files = folder.listFiles();
        List<String> all = new ArrayList<>();
        for (File file : files) {
            all.add(file.getName().substring(0, file.getName().lastIndexOf(".png")));
        }
        return R.ok(all);
    }

    @ApiOperation("修改轮播图")
    @PostMapping("/updateCarousel")
    public R updateCarousel(@RequestBody Carousel carousel) throws IOException {
        carouselService.updateById(carousel);
        return R.ok();
    }

    @ApiOperation("轮播图图片上传")
    @PostMapping(value = "/uploadCarouseImages", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R uploadAvatarImages(@RequestParam("file") MultipartFile file) throws IOException {

        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return R.error("请选择jpg,jpeg,gif,png格式的图片");
        }
        String savePath = "data/images/swipers/";
        long fileId = System.currentTimeMillis();
        String filename = fileId + "." + "png";

        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(System.getProperty("user.dir") + "/src/main/resources/" + savePath + filename));
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(System.getProperty("user.dir") + "/target/classes/" + savePath + filename));
        return R.ok("swipers/" + fileId);
    }


    @ApiOperation("获取当前图书馆所有订单列表")
    @GetMapping("/orderList")
    public R<List<Order>> getOrderListForUserId(HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        LambdaQueryWrapper<Library> lambdaQueryWrapperLibrary = new LambdaQueryWrapper<>();
        lambdaQueryWrapperLibrary.eq(Library::getAdministratorId, userId);

        List<Library> libraries = libraryService.list(lambdaQueryWrapperLibrary);
        Library library = libraries.get(0);

        LambdaQueryWrapper<Order> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Order::getLibraryId, library.getId());
        List<Order> orders = orderService.list(lambdaQueryWrapper);
        orders.replaceAll(e -> {
            e.setAdminName(adminMapper.selectById(e.getAdminid()).getUsername());
            e.setLibraryName(library.getLibraryname());
            Product product = productService.getById(e.getProductid());
            e.setProductName(product.getProductname());
            e.setPrice(product.getPrice());
            e.setPhoto(product.getPhoto());
            return e;
        });
        return R.ok(orders);
    }

    @ApiOperation("获取当前图书馆预定信息")
    @GetMapping("/librarySeatList")
    public R<List<LibrarySeatDetail>> getLibrarySeatDetail(HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        LambdaQueryWrapper<Library> lambdaQueryWrapperLibrary = new LambdaQueryWrapper<>();
        lambdaQueryWrapperLibrary.eq(Library::getAdministratorId, userId);

        List<Library> libraries = libraryService.list(lambdaQueryWrapperLibrary);
        Library library = libraries.get(0);

        LambdaQueryWrapper<LibrarySeatDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LibrarySeatDetail::getLibraryid, library.getId());
        List<LibrarySeatDetail> librarySeatDetail = librarySeatDetailMapper.selectList(lambdaQueryWrapper);
        librarySeatDetail.replaceAll(e -> {
            e.setAdminName(adminMapper.selectById(e.getUserId()).getUsername());
            e.setLibraryName(library.getLibraryname());
            e.setLibraryAddress(library.getAddress());
            return e;
        });
        return R.ok(librarySeatDetail);
    }

    @ApiOperation("根据图书馆管理员id获取图书馆信息")
    @GetMapping("/getLibraryById/{id}")
    public R<Library> getLibraryById(@PathVariable("id") Integer id) {
        LambdaQueryWrapper<Library> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Library::getAdministratorId, id);

        List<Library> library = libraryService.list(lambdaQueryWrapper);
        return R.ok(library.get(0));
    }

    @ApiOperation("获取当前管理图书馆信息")
    @GetMapping("/getLibraryInfo")
    public R<Library> getLibraryInfo(HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        LambdaQueryWrapper<Library> lambdaQueryWrapperLibrary = new LambdaQueryWrapper<>();
        lambdaQueryWrapperLibrary.eq(Library::getAdministratorId, userId);

        List<Library> libraries = libraryService.list(lambdaQueryWrapperLibrary);
        Library library = libraries.get(0);
        return R.ok(library);
    }

    @ApiOperation("删除订单")
    @GetMapping("/deleteOrder/{id}")
    public R deleteOrder(@PathVariable("id") Integer id) {
        orderService.removeById(id);
        return R.ok();
    }

    @ApiOperation("删除评论")
    @GetMapping("/deleteComment/{id}")
    public R deleteComment(@PathVariable("id") Integer id) {
        commentService.removeById(id);
        return R.ok();
    }

    @ApiOperation("删除商品")
    @GetMapping("/deleteProduct/{id}")
    public R deleteProduct(@PathVariable("id") Integer id) {
        productService.removeById(id);
        return R.ok();
    }

    @ApiOperation("删除座位预定")
    @GetMapping("/deleteLibrarySeat/{id}")
    public R deleteLibrarySeat(@PathVariable("id") Integer id) {
        librarySeatDetailMapper.deleteById(id);
        return R.ok();
    }

    @ApiOperation("获取所有图书馆")
    @GetMapping("/getLibraryList")
    public R<List<Library>> getLibraryList() {
        List<Library> libraryList = libraryService.list();
        return R.ok(libraryList);
    }

    @ApiOperation("图书馆绑定管理员")
    @GetMapping("/setLibraryadministrator/{libraryId}/{adminId}")
    public R setLibraryadministrator(@PathVariable("libraryId") Integer libraryId, @PathVariable("adminId") Integer adminId) {
        Library library = libraryService.getById(libraryId);
        library.setAdministratorId(adminId);
        libraryService.saveOrUpdate(library);
        return R.ok();
    }

    @ApiOperation("获取当前图书馆商品信息")
    @GetMapping("/getProductList")
    public R<List<Product>> getProductList(HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        LambdaQueryWrapper<Library> lambdaQueryWrapperLibrary = new LambdaQueryWrapper<>();
        lambdaQueryWrapperLibrary.eq(Library::getAdministratorId, userId);

        List<Library> libraries = libraryService.list(lambdaQueryWrapperLibrary);
        Library library = libraries.get(0);

        LambdaQueryWrapper<Product> lambdaQueryWrapperProduct = new LambdaQueryWrapper<>();
        lambdaQueryWrapperProduct.eq(Product::getLibraryId, library.getId());

        List<Product> list = productService.list(lambdaQueryWrapperProduct);
        list.replaceAll(e -> {
            e.setLibraryName(library.getLibraryname());
            return e;
        });
        return R.ok(list);
    }


    @ApiOperation("修改座椅状态")
    @GetMapping("/seatChange/{time}/{seatId}/{data}")
    public R seatChange(HttpServletRequest request, @PathVariable("time") String time, @PathVariable("seatId") Integer seatId, @PathVariable("data") String data) {
        String userId = (String) request.getAttribute("userId");
        LambdaQueryWrapper<Library> lambdaQueryWrapperLibrary = new LambdaQueryWrapper<>();
        lambdaQueryWrapperLibrary.eq(Library::getAdministratorId, userId);

        List<Library> libraries = libraryService.list(lambdaQueryWrapperLibrary);
        Library library = libraries.get(0);


        LibrarySeatDetail librarySeatDetail = new LibrarySeatDetail();
        librarySeatDetail.setStatus(time);
        librarySeatDetail.setUserId(Integer.valueOf(userId));
        librarySeatDetail.setSeatId(seatId);
        librarySeatDetail.setLibraryid(library.getId());
        librarySeatDetail.setSeatTime(data);
        librarySeatDetail.setCreatTime(new Date());
        librarySeatDetail.setFlag("1");
        librarySeatDetailMapper.insert(librarySeatDetail);
        return R.ok();
    }

    @ApiOperation("修改当前管理图书馆信息")
    @GetMapping("/updateLibraryInfo/{libraryName}/{area}/{address}")
    public R<Library> updateLibraryInfo(HttpServletRequest request, @PathVariable("libraryName") String libraryName, @PathVariable("area") String area, @PathVariable("address") String address) {
        String userId = (String) request.getAttribute("userId");
        LambdaQueryWrapper<Library> lambdaQueryWrapperLibrary = new LambdaQueryWrapper<>();
        lambdaQueryWrapperLibrary.eq(Library::getAdministratorId, userId);
        List<Library> libraries = libraryService.list(lambdaQueryWrapperLibrary);
        Library library = libraries.get(0);
        library.setLibraryname(libraryName);
        library.setAddress(address);
        library.setArea(area);
        libraryService.saveOrUpdate(library);
        return R.ok();
    }

    @ApiOperation("添加商品信息")
    @PostMapping("/addProduct")
    public R addProduct(HttpServletRequest request, @RequestBody Product product) {
        String userId = (String) request.getAttribute("userId");
        LambdaQueryWrapper<Library> lambdaQueryWrapperLibrary = new LambdaQueryWrapper<>();
        lambdaQueryWrapperLibrary.eq(Library::getAdministratorId, userId);
        List<Library> libraries = libraryService.list(lambdaQueryWrapperLibrary);
        Library library = libraries.get(0);

        product.setId(null);
        product.setLibraryId(library.getId());

        productService.saveOrUpdate(product);

        return R.ok();
    }

    @ApiOperation("修改商品信息")
    @PostMapping("/updateProduct")
    public R updateProduct(HttpServletRequest request, @RequestBody Product product) {
        String userId = (String) request.getAttribute("userId");
        LambdaQueryWrapper<Library> lambdaQueryWrapperLibrary = new LambdaQueryWrapper<>();
        lambdaQueryWrapperLibrary.eq(Library::getAdministratorId, userId);
        List<Library> libraries = libraryService.list(lambdaQueryWrapperLibrary);
        Library library = libraries.get(0);
        product.setLibraryId(library.getId());
        productService.saveOrUpdate(product);
        return R.ok();
    }

    @ApiOperation("添加图书馆信息")
    @PostMapping("/addLibraryInfo")
    public R<Library> addLibraryInfo(HttpServletRequest request, @RequestBody Library library) {
        library.setId(null);
        libraryService.saveOrUpdate(library);
        return R.ok();
    }

    @ApiOperation("修改图书馆信息")
    @PostMapping("/updateLibrary")
    public R<Library> updateLibrary(HttpServletRequest request, @RequestBody Library library) {
        Library library1 = libraryService.getById(library.getId());
        library1.setLibraryname(library.getLibraryname());
        library1.setArea(library.getArea());
        library1.setAddress(library.getAddress());
        library1.setPhoto(library.getPhoto());
        libraryService.saveOrUpdate(library1);
        return R.ok();
    }


    @ApiOperation("删除预定座位信息")
    @GetMapping("/deleteSeatReserve/{time}/{seatId}/{data}")
    public R<Library> deleteSeatReserve(HttpServletRequest request, @PathVariable("time") String time, @PathVariable("seatId") Integer seatId, @PathVariable("data") String data) {
        String userId = (String) request.getAttribute("userId");
        LambdaQueryWrapper<Library> lambdaQueryWrapperLibrary = new LambdaQueryWrapper<>();
        lambdaQueryWrapperLibrary.eq(Library::getAdministratorId, userId);
        List<Library> libraries = libraryService.list(lambdaQueryWrapperLibrary);
        Library library = libraries.get(0);
        LambdaQueryWrapper<LibrarySeatDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LibrarySeatDetail::getLibraryid, library.getId())
                .eq(LibrarySeatDetail::getSeatId,seatId)
                .eq(LibrarySeatDetail::getSeatTime,data)
                .eq(LibrarySeatDetail::getStatus,time);
        List<LibrarySeatDetail> librarySeatDetails = librarySeatDetailMapper.selectList(lambdaQueryWrapper);
        if(librarySeatDetails!=null)
        librarySeatDetailMapper.deleteById(librarySeatDetails.get(0).getId());
        return R.ok();
    }



}
